package com.example.demo.controller;

import com.example.demo.common.AppVariable;
import com.example.demo.common.PasswordUtils;
import com.example.demo.common.ResultAjax;
import com.example.demo.common.SessionUtils;
import com.example.demo.model.Userinfo;
import com.example.demo.model.vo.UserinfoVO;
import com.example.demo.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserService userService;

    @RequestMapping("/reg")
    public ResultAjax reg(Userinfo userinfo){
        if(userinfo==null||!StringUtils.hasLength(userinfo.getUsername())||!StringUtils.hasLength(userinfo.getPassword())){
            return ResultAjax.fail(-1,"参数错误");
        }
        userinfo.setPassword(PasswordUtils.encrypt(userinfo.getPassword()));
        int result=userService.reg(userinfo);
        return ResultAjax.succ(result);
    }

    @RequestMapping("/login")
    public ResultAjax login(Userinfo userinfo,HttpServletRequest request){
        if(userinfo==null||!StringUtils.hasLength(userinfo.getUsername())||!StringUtils.hasLength(userinfo.getPassword())){
            return ResultAjax.fail(-1,"参数错误");
        }
        Userinfo userinfo1=userService.getUserByName(userinfo.getUsername());
        if(userinfo1==null||userinfo1.getId()==0){
            return ResultAjax.fail(-2,"用户名或密码错误");
        }
        if(!PasswordUtils.decrypt(userinfo.getPassword(),userinfo1.getPassword())){
            return ResultAjax.fail(-2,"用户名或密码有误");
        }
        HttpSession session=request.getSession();
        session.setAttribute(AppVariable.SESSION_USERINFO_KEY,userinfo1);
        return ResultAjax.succ(1);
    }

    @RequestMapping("/logout")
    public ResultAjax logout(HttpServletRequest request){
        HttpSession session=request.getSession();
        if(session!=null&&session.getAttribute(AppVariable.SESSION_USERINFO_KEY)!=null){
            session.removeAttribute(AppVariable.SESSION_USERINFO_KEY);
        }
        return ResultAjax.succ(1);
    }
}
